<template>
  <div class="container">
    <div class="text-center upload-box">
      <div>
        <el-upload ref="rebateUpload"
                   class="upload-demo"
                   drag
                   :action="upload"
                   name="excel"
                   :limit="1"
                   :before-upload="beforeUpload"
                   :headers="headerUpload"
                   :on-success="handleSuccess"
                   :on-remove="handleRemove"
                   :show-file-list="false"
                   :on-error="handleError"
                   v-show="isShowUpload">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">{{$t('page.drop')}}，<em>{{$t('page.click')}}</em></div>
        </el-upload>
        <div class="reset-back"
             v-if="isShowStepOne">
          <div class="link"
               @click="changLogData">{{$t('page.modData')}}</div>
          <span class="link"
                @click="handleRemove">{{$t('page.emptyData')}}</span>
        </div>
        <div class="upload-name-box">
          <div class="upload-name"
               v-show="isShowUploadtxt">
            {{uploadFile.name}}
            <el-button type='text'
                       @click="handleRemove()">x</el-button>
          </div>
          <el-progress :percentage="percentage"
                       :color="customColor"
                       v-show="isShowPer"></el-progress>
        </div>
      </div>
    </div>

    <div class="container-body"
         v-if="isShowStepOne">
      <template>
        <div class="title-space">
          <span>{{$t('page.ODvalue')}}：</span>
        </div>
        <div v-for="(listItem,listIndex) in originalData">
          <div class="overflow">
            <table id="table-1">

              <tr v-for="(table,key,index) in listItem"
                  :key="index">
                <td class="color-000">{{key!=='time'?key:$t('page.hole')}}</td>
                <td>
                  <span v-if="key!=='time'">
                    {{beforeLable[index-1]}}
                  </span>
                  <span class="color-000"
                        v-else>{{$t('page.label')}}({{unit}})
                  </span>
                </td>
                <td v-for="iTable in table">
                  <span v-if="key!=='time'">{{iTable}}</span>
                  <span class="color-000"
                        v-else>{{iTable + 's'}}</span>
                </td>
              </tr>
            </table>
          </div>

          <div class="space"
               v-if="dissType === 'v1'">
            <div class="title-space">
              <span>{{$t('page.ODrate')}}（%）： </span>
            </div>

            <div class="overflow"
                 v-for="lightRateItem,lightRateIndex in lightRate">
              <table id="table-1">
                <tr v-for="(table,key,index) in lightRateItem"
                    :key="index">
                  <td class="color-000">{{key!=='time'?key:$t('page.hole')}}</td>
                  <td>
                    <span v-if="key!=='time'">
                      {{beforeLable[index-1]}}{{unit}}
                    </span>
                    <span class="color-000"
                          v-else>
                      {{$t('page.parameter')}}
                    </span>
                  </td>
                  <td v-for="iTable in table">
                    <span v-if="key!=='time'">{{iTable}}</span>
                    <span class="color-000"
                          v-else>{{iTable + 's'}}</span>
                  </td>
                </tr>
              </table>
            </div>
          </div>

          <div class="space text-center">
            <template v-for="(chart,index) in allLightRateCharts">
              <div class="chart">
                <wave-chart :id="'LightRate1'+index"
                            :data='chart'></wave-chart>
              </div>
            </template>
          </div>

          <div class="space text-center">
            <template v-for="(chart,index) in allStepOneCharts"
                      v-if="index === listIndex">
              <wave-chart :id="'logStepOne1'+index"
                          :data='chart'></wave-chart>
            </template>
          </div>
        </div>

        <div class="title-space">
          <span>{{$t('page.calResultes')}}：</span>
          <el-button type="text"
                     @click="downloadExl()"
                     size="mini">{{$t('page.export')}}</el-button>
        </div>

        <div class="title-space">
          <span>{{$t('page.molecular')}}（Da）：</span>
          {{mole}}
        </div>

        <div class="space"
             v-show="isShowStepTwo">

          <div v-if="dissType === 'v1'">
            <div class="overflow step-two">
              <table id="table-1">
                <template v-for="stepTwoItem,TwoIndex in stepTwoList">
                  <tr :key="TwoIndex"
                      v-for="(table,key,index) in stepTwoItem">
                    <td class="color-000">
                      <span v-if="key!=='title'">{{key}}</span>
                      <span v-else>{{$t('page.hole')}}</span>
                    </td>
                    <td v-for="iTable in table"
                        v-if="key ==='title'"
                        class="color-000">
                      <span v-html="iTable"></span>
                    </td>
                    <td v-for="iTable in table"
                        v-if="key !=='title'">
                      <span :style="{color:iTable===extA?'#409eff':''}"
                            v-if="iTable===extA"> ({{$t('page.recommended')}}){{iTable}}</span>
                      <span v-else> {{iTable}}</span>
                    </td>
                  </tr>
                </template>
              </table>
            </div>

            <div class="img-list"
                 v-for="img,index in imgList"
                 :key="index"
                 style="width:60%;float:left;">
              <div class="img-item">
                <img :src="img"
                     alt="">
              </div>
            </div>

            <div style="width:40%;float:left;padding-left:50px;margin-top:25px;">
              <table id="table-2">
                <tr>
                  <td width="50%">
                    {{$t('page.formula')}}
                  </td>
                  <td>
                    y=x*Rmax/(x+KD)
                  </td>
                </tr>
                <tr>
                  <td width="50%">{{$t('page.parameter')}}</td>
                  <td>
                    <span class="data-item">Ka:{{parameter[1]}}</span>
                    <span class="data-item">Kd:{{parameter[2]}}</span>
                    <span class="data-item">KD:{{parameter[3]}}</span>
                  </td>
                </tr>

                <tr>
                  <td width="50%">{{$t('page.parameter')}}</td>
                  <td>
                    <span class="data-item">{{parameter[0]}}</span>
                  </td>
                </tr>
              </table>
            </div>
          </div>
          <div v-else>
            <div class="overflow">
              <table id="table-1">

                <template v-for="resValue,resIndex in paramResult">
                  <tr>
                    <td v-for="v,k,i in resValue">{{k}}</td>
                  </tr>
                  <tr>
                    <td v-for="v,k,i in resValue">{{v}}</td>
                  </tr>
                </template>
              </table>
            </div>
          </div>

        </div>
      </template>

      <div class="space text-center">
      </div>
    </div>

    <!------------------ 截图曲线 -->
    <div class="m-top-fff"
         v-if="showScreenshotsImg">
      <template v-for="(chart,index) in allStepOneCharts">
        <wave-chart :id="'logStepOne'+index"
                    :data='chart'
                    @shotImg="shotImg"></wave-chart>
      </template>
    </div>

    <el-dialog :visible.sync="isShowInputLog"
               :close-on-click-modal="false"
               :before-close="handleRemove"
               width="90%"
               top="5%"
               center>
      <div>
        <div class="title-space">
          <span>{{$t('page.unit')}}</span>
        </div>
        <el-radio-group v-model="unit">
          <el-radio :label="v"
                    v-for="v,i in unitOption"
                    :key="i"></el-radio>
        </el-radio-group>

        <div class="title-space">
          <span>{{$t('page.label')}}({{unit}})</span>
        </div>
        <table id="table-1">
          <tr>
            <td v-for="(table,index) in waveName"
                width="50">
              {{table}}
            </td>
          </tr>
          <tr>
            <td v-for="(table,index) in waveName">
              <el-input type="Number"
                        v-model="beforeLable[index]"></el-input>
            </td>
          </tr>
        </table>

        <div class="space text-center">
          <div class="title-space">
            <span>{{$t('page.molecular')}}（Da）：</span>
            <el-input type="number"
                      class="input"
                      v-model="mole"
                      style="width:500px;">
            </el-input>
          </div>
        </div>

        <div class="space text-center">
          <el-button type="primary"
                     @click="handleCompute()"
                     size="small"
                     :loading="computeLoading"
                     class="btn-submit-color">{{$t('page.submit')}}</el-button>
        </div>

      </div>
    </el-dialog>

  </div>
</template>
<script>
import waveChart from '@/components/WaveChart'
import { fetchAffinityStep2, fetchUploadExl } from '@/api/table'
import { setStore, getStore } from '@/utils/common'
import { getToken } from '@/utils/auth'
import store from '@/store'

export default {
  data() {
    return {
      originalData: [],
      originalDataRate: [],
      lightRate: [],
      lightValue: [],
      stepTwoList: [],
      computeLoading: false, //显示计算loading
      computeAllowed: true, //防连点
      isShowInputLog: false, //是否显示公式
      isShowStepOne: false, //是否显示第一步表格
      isShowStepTwo: false, //是否显示第二步表格
      showScreenshotsImg: true, //页面上的曲线隐藏
      isShowUpload: true,
      isShowUploadtxt: false,
      uploadFile: {},
      mole: '115207373',
      unit: 'ug/ml',
      unitOption: ['pg/ml', 'ng/ml', 'ug/ml', 'mg/ml'],
      isShowPer: false,
      percentage: 0,
      customColor: '#e6a23c',
      allLightRateCharts: [],
      allStepOneCharts: [],
      isRepeatSubmit: false,
      extA: '',
      imgList: '',
      unitTitle: [],
      parameter: [],
      waveName: [],
      beforeLable: [],
      baseStepOne: [],
      doDownload: false,
      paramResult: [],
      dissociation: [],
      dissType: '',
    }
  },
  components: {
    waveChart,
  },
  methods: {
    goNext(route, type) {
      if (type === 1) {
        setStore('chartData', this.lightRate)
      }
      this.$router.push({ path: route })
    },
    changLogData() {
      this.isRepeatSubmit = true
      this.isShowInputLog = true
      this.doDownload = false
      this.beforeLable = []
    },
    beforeUpload(file) {
      this.uploadFile = file
      this.isShowPer = true
      this.isShowUpload = false
      this.isShowUploadtxt = true
      this.percentage += 60 + Math.floor(Math.random() * 10)
    },
    handleSuccess(file, filelist) {
      // file = {
      const next = 100 - this.percentage
      this.percentage += next
      setTimeout(() => {
        this.isShowPer = false
      }, 1000)
      if (file.status === 200) {
        this.waveName = file.data.hole
        this.isShowInputLog = true
        // this.beforeLable = []
        // this.waveName.forEach((item) => {
        //   this.beforeLable.push('')
        // })

        setStore('auuid', file.data.uuid)
      } else {
        if (file.status === 502) {
          this.$msgbox
            .confirm(this.$t('page.msgBoxLoginOut'), this.$t('page.loginOut'), {
              confirmButtonText: this.$t('page.loginAgin'),
              cancelButtonText: this.$t('page.cancel'),
              type: 'warning',
            })
            .then(() => {
              store.dispatch('FedLogOut').then(() => {
                location.reload()
              })
            })
        } else {
          this.$message.error(file.msg)
        }
      }
    },
    handleError(err) {
      this.$message.error(err)
    },
    async handleCompute() {
      if (this.computeAllowed) {
        this.showScreenshotsImg = true
        this.baseStepOne = []
        let info = await fetchAffinityStep2({
          crpValue: this.beforeLable,
          uuid: getStore('auuid'),
          mole: this.mole,
          unit: this.unit,
          isRepeatSubmit: this.isRepeatSubmit,
        })
        if (info.status === 200) {
          this.paramResult = []
          this.originalData = []
          this.originalData = info.data.originalData
          this.paramResult = info.data.paramResult
          this.dissociation = info.data.dissociation
          this.dissType = info.data.extB
          if (this.isRepeatSubmit) {
            setStore('auuid', info.data.uuid)
          }

          //v1是旧表，v2是新表
          if (this.dissType === 'v1') {
            this.lightRate = info.data.lightRate
            this.stepTwoList = []
            this.stepTwoList = info.data.finalResult

            this.imgList = info.data.imgList
            this.extA = info.data.extA
            let loctionTitle = info.data.unitTitle
            loctionTitle.forEach((item) => {
              let title = []
              item.forEach((titleItem, index) => {
                if (index === 4) {
                  const sub = `K<sub>a</sub>(10<sup>${titleItem}</sup>M<sup>-1</sup>S<sup>-1</sup>)`
                  title.push(sub)
                } else if (index === 5) {
                  const sub = `K<sub>d</sub>(10<sup>${titleItem}</sup>S<sup>-1</sup>)`
                  title.push(sub)
                } else if (index === 6) {
                  const sub = `K<sub>D</sub>(10<sup>${titleItem}</sup>S<sup>-1</sup>)`
                  title.push(sub)
                } else {
                  title.push(titleItem)
                }
              })
              const data = {}
              data.equa = title
              this.unitTitle.push(data)
            })

            this.stepTwoList.forEach((dataListItem) => {
              for (let i in dataListItem) {
                if (dataListItem[i].indexOf(this.extA) === 0) {
                  this.parameter = dataListItem[i]
                }
              }
            })
            const stepTwoTitle = { title: this.unitTitle[0].equa }
            this.stepTwoList.unshift(stepTwoTitle)
            this.stepTwoList.map((listItem) => {
              for (let i in listItem) {
                listItem[i].splice(1, 3)
              }
            })
          }

          this.newDrawChart()

          let _this = this
          _this.$nextTick(() => {
            setTimeout(() => {
              _this.imgUpLoad()
              _this.doDownload = true
            }, 3000)
          })

          this.isShowInputLog = false
          this.isShowStepOne = true
          this.isShowStepTwo = true
        } else {
          this.$message.error(info.msg)
        }
      }
    },
    async imgUpLoad() {
      await fetchUploadExl({
        crpValue: this.beforeLable,
        uuid: getStore('auuid'),
        mole: this.mole,
        imgBase64: this.baseStepOne,
      })
    },
    handleRemove() {
      this.$refs['rebateUpload'].clearFiles() //清除文件
      //上传框
      this.isShowUpload = true
      this.isShowUploadtxt = false
      //可以计算
      this.computeAllowed = true
      this.computeLoading = false
      //上传进度条
      this.percentage = 0
      //显示进度
      this.isShowPer = false
      this.paramResult = []
      this.originalData = []
      this.stepTwoList = []
      this.allStepOneCharts = []
      this.isShowStepOne = false
      this.isShowStepTwo = false
      this.isShowInputLog = false
      this.doDownload = false
      this.baseStepOne = []
      this.beforeLable = []
      this.unit = 'ug/ml'
      this.mole = '115207373'
    },
    sortObj(obj) {
      var arr = []
      for (var i in obj) {
        arr.push([obj[i], i])
      }
      arr.reverse()
      var len = arr.length
      var obj = {}
      for (var i = 0; i < len; i++) {
        obj[arr[i][1]] = arr[i][0]
      }
      return obj
    },
    downloadExl() {
      if (this.isShowStepTwo && this.doDownload) {
        const href = `${
          process.env.BASE_URL
        }receive/download/excel/1/${getStore('auuid')}`
        window.open(href, '_blank')
      } else {
        this.$message({
          type: 'error',
          message: this.$t('page.doDownload'),
        })
      }
    },
    opens() {
      setTimeout(() => {
        let triggerResize = new Event('resize')
        window.dispatchEvent(triggerResize)
      }, 0)
    },
    newDrawChart() {
      const dissocArry = this.dissociation
      const disscoType = this.dissType
      this.allLightRateCharts = []
      this.allStepOneCharts = []
      this.lightRate.forEach((item, index, arry) => {
        let chartsOption = {
          title: {
            text: '',
          },
          animation: false,
          tooltip: {
            trigger: 'axis',
          },
          legend: {
            data: [],
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true,
          },
          toolbox: {
            feature: {
              saveAsImage: {},
            },
          },
          xAxis: {
            type: 'category',
            axisTick: {
              alignWithLabel: true,
            },
            axisLine: {
              onZero: false,
            },
            boundaryGap: false,
            data: [],
          },
          yAxis: {
            type: 'value',
          },
          series: [],
        }
        chartsOption.series = []
        chartsOption.xAxis.data = []
        let num = 0
        for (let i in item) {
          if (i !== 'time') {
            let chartSeries = {
              name: `${this.beforeLable[num] + this.unit}`,
              type: 'line',
              smooth: true,
              showSymbol: false,
              hoverAnimation: false,
              data: item[i],
            }
            chartsOption.title.text =
              this.$t('page.ODrate') + this.$t('page.curve')
            chartsOption.legend.data.push(
              `${this.beforeLable[num] + this.unit}`
            )
            chartsOption.series.push(chartSeries)
            num++
          } else {
            chartsOption.xAxis.data = item[i]
          }
        }
        this.allLightRateCharts.push(chartsOption)
      })
      console.log(this.allLightRateCharts)
      this.originalData.forEach((item, index, arry) => {
        let chartsOption = {
          title: {
            text: '',
          },
          animation: false,
          tooltip: {
            trigger: 'axis',
          },
          legend: {
            data: [],
          },
          grid: {
            left: '3%',
            right: '5%',
            bottom: '15%',
            containLabel: true,
          },
          dataZoom: [
            {
              type: 'slider',
              xAxisIndex: 0,
              filterMode: 'empty',
            },
            {
              type: 'slider',
              yAxisIndex: 0,
              filterMode: 'empty',
            },
          ],
          toolbox: {
            feature: {
              saveAsImage: {},
            },
          },
          xAxis: {
            type: 'category',
            axisTick: {
              alignWithLabel: true,
            },
            boundaryGap: false,
            minInterval: 120,
            data: [],
          },
          yAxis: {
            type: 'value',
          },
          series: [],
          markLine: {},
        }
        chartsOption.series = []
        chartsOption.xAxis.data = []
        let num = 0
        let newDissToString = ''
        if (disscoType === 'v2') {
          let dissocIndex = dissocArry[index]
          let newDissocItem = ''
          for (let i in item) {
            if (i === 'time') {
              newDissocItem = item[i][dissocIndex]
              newDissToString = newDissocItem.toString()
            }
          }
          for (let i in item) {
            if (i !== 'time') {
              let chartSeries = {
                name: `${this.beforeLable[num] + this.unit}`,
                type: 'line',
                smooth: true,
                showSymbol: false,
                hoverAnimation: false,
                data: item[i],
                markLine: {
                  symbol: 'none',
                  lineStyle: {
                    normal: {
                      color: '#000',
                    },
                  },
                  data: [
                    {
                      xAxis: newDissToString,
                    },
                  ],
                  label: {
                    normal: {
                      formatter: newDissToString,
                    },
                  },
                },
              }
              chartsOption.title.text =
                this.$t('page.ODvalue') + this.$t('page.curve')
              chartsOption.legend.data.push(
                `${this.beforeLable[num] + this.unit}`
              )
              chartsOption.series.push(chartSeries)
              num++
            } else {
              chartsOption.xAxis.data = item[i]
            }
          }
        } else {
          for (let i in item) {
            if (i !== 'time') {
              let chartSeries = {
                name: `${this.beforeLable[num] + this.unit}`,
                type: 'line',
                smooth: true,
                showSymbol: false,
                hoverAnimation: false,
                data: item[i],
              }
              chartsOption.title.text =
                this.$t('page.ODvalue') + this.$t('page.curve')
              chartsOption.legend.data.push(
                `${this.beforeLable[num] + this.unit}`
              )
              chartsOption.series.push(chartSeries)
              num++
            } else {
              chartsOption.xAxis.data = item[i]
            }
          }
        }

        this.allStepOneCharts.push(chartsOption)
      })

      let _this = this
      setTimeout(() => {
        _this.showScreenshotsImg = false
      }, 1500)
    },
    shotImg(data) {
      this.baseStepOne.push(data)
    },
  },
  computed: {
    upload: () => {
      return `${process.env.BASE_URL}receive/affinity/upload/step1`
    },
    headerUpload: () => {
      const data = {}
      data.TOKEN = getToken()
      if (localStorage.getItem('spr-lang') === 'en') {
        data.LANG = 'ENG' // 传语言
      }
      return data
    },
  },
}
</script>

<style lang="scss" scoped>
table {
  border-collapse: collapse;
  text-align: center;
  white-space: nowrap;
  margin-bottom: 20px;
}
.reset-back {
  display: flex;
  align-items: center;
  margin: 0 20px 20px;
  .link {
    cursor: pointer;
    color: #409eff;
    font-style: normal;
    margin-right: 20px;
  }
}
.img-list {
  width: 1000px;
  display: flex;
  flex-wrap: wrap;
}
.img-item {
  width: 500px;
}

#table-2 {
  border-bottom-width: 1px;
  border-bottom-style: solid;
  border-bottom-color: #000;
}
#table-2 tr {
  border: 1px solid #000 !important;
}

#table-2 td:first-child {
  border-left: 1px solid #000;
}

/* Padding and font style */
#table-2 td,
#table-2 th {
  padding: 10px 15px;
  font-size: 12px;
  font-family: Verdana;
  border-right-width: 1px;
  border-right-style: solid;
}

.data-item {
  display: block;
}

@media screen and (min-width: 1000px) {
  .data-item {
    display: inline-block;
    margin-right: 20px;
  }
}
</style>